<?php
/**
 * 用户类
 */
class User {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance();
    }
    
    /**
     * 注册新用户
     * 
     * @param string $username 用户名
     * @param string $email 邮箱
     * @param string $phone 手机号
     * @param string $password 密码
     * @param string $nickname 昵称
     * @return array 包含状态和消息的数组
     */
    public function register($username, $email, $phone, $password, $nickname = '') {
        // 验证用户名
        if (empty($username) || strlen($username) < 3 || strlen($username) > 20) {
            return ['status' => false, 'message' => '用户名长度应为3-20个字符'];
        }
        
        // 验证邮箱
        if (empty($email) || !validateEmail($email)) {
            return ['status' => false, 'message' => '请提供有效的邮箱地址'];
        }
        
        // 验证手机号
        if (!empty($phone) && !validatePhone($phone)) {
            return ['status' => false, 'message' => '请提供有效的手机号码'];
        }
        
        // 验证密码
        if (empty($password) || strlen($password) < 6) {
            return ['status' => false, 'message' => '密码长度至少为6个字符'];
        }
        
        // 检查用户名是否已存在
        $existingUser = $this->db->fetch("SELECT id FROM users WHERE username = ?", [$username]);
        if ($existingUser) {
            return ['status' => false, 'message' => '用户名已被使用'];
        }
        
        // 检查邮箱是否已存在
        $existingEmail = $this->db->fetch("SELECT id FROM users WHERE email = ?", [$email]);
        if ($existingEmail) {
            return ['status' => false, 'message' => '邮箱已被注册'];
        }
        
        // 检查手机号是否已存在
        if (!empty($phone)) {
            $existingPhone = $this->db->fetch("SELECT id FROM users WHERE phone = ?", [$phone]);
            if ($existingPhone) {
                return ['status' => false, 'message' => '手机号已被注册'];
            }
        }
        
        // 设置默认昵称
        if (empty($nickname)) {
            $nickname = $username;
        }
        
        // 密码加密
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        
        // 插入用户数据
        try {
            $this->db->query(
                "INSERT INTO users (username, email, phone, password, nickname) VALUES (?, ?, ?, ?, ?)",
                [$username, $email, $phone, $hashedPassword, $nickname]
            );
            
            return [
                'status' => true,
                'message' => '注册成功，请登录',
                'user_id' => $this->db->lastInsertId()
            ];
        } catch (Exception $e) {
            return ['status' => false, 'message' => '注册失败，请稍后再试'];
        }
    }
    
    /**
     * 用户登录
     * 
     * @param string $identity 用户名/邮箱/手机号
     * @param string $password 密码
     * @return array 包含状态和消息的数组
     */
    public function login($identity, $password) {
        if (empty($identity) || empty($password)) {
            return ['status' => false, 'message' => '请输入用户名/邮箱/手机号和密码'];
        }
        
        // 查找用户
        $user = $this->db->fetch(
            "SELECT * FROM users WHERE username = ? OR email = ? OR phone = ?",
            [$identity, $identity, $identity]
        );
        
        if (!$user) {
            return ['status' => false, 'message' => '用户不存在'];
        }
        
        // 验证密码
        if (!password_verify($password, $user['password'])) {
            return ['status' => false, 'message' => '密码错误'];
        }
        
        // 登录成功
        $_SESSION['user_id'] = $user['id'];
        
        return [
            'status' => true,
            'message' => '登录成功',
            'user' => $user
        ];
    }
    
    /**
     * 更新用户信息
     * 
     * @param int $userId 用户ID
     * @param array $data 要更新的数据
     * @return array 包含状态和消息的数组
     */
    public function updateProfile($userId, $data) {
        $allowedFields = ['nickname', 'avatar', 'bio'];
        $updateData = [];
        $params = [];
        
        foreach ($data as $key => $value) {
            if (in_array($key, $allowedFields)) {
                $updateData[] = "$key = ?";
                $params[] = $value;
            }
        }
        
        if (empty($updateData)) {
            return ['status' => false, 'message' => '没有要更新的数据'];
        }
        
        $params[] = $userId;
        
        try {
            $this->db->query(
                "UPDATE users SET " . implode(', ', $updateData) . " WHERE id = ?",
                $params
            );
            
            return ['status' => true, 'message' => '个人资料已更新'];
        } catch (Exception $e) {
            return ['status' => false, 'message' => '更新失败，请稍后再试'];
        }
    }
    
    /**
     * 修改密码
     * 
     * @param int $userId 用户ID
     * @param string $currentPassword 当前密码
     * @param string $newPassword 新密码
     * @return array 包含状态和消息的数组
     */
    public function changePassword($userId, $currentPassword, $newPassword) {
        // 获取用户信息
        $user = $this->db->fetch("SELECT * FROM users WHERE id = ?", [$userId]);
        
        if (!$user) {
            return ['status' => false, 'message' => '用户不存在'];
        }
        
        // 验证当前密码
        if (!password_verify($currentPassword, $user['password'])) {
            return ['status' => false, 'message' => '当前密码错误'];
        }
        
        // 验证新密码
        if (empty($newPassword) || strlen($newPassword) < 6) {
            return ['status' => false, 'message' => '新密码长度至少为6个字符'];
        }
        
        // 更新密码
        $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
        
        try {
            $this->db->query(
                "UPDATE users SET password = ? WHERE id = ?",
                [$hashedPassword, $userId]
            );
            
            return ['status' => true, 'message' => '密码已更新'];
        } catch (Exception $e) {
            return ['status' => false, 'message' => '更新失败，请稍后再试'];
        }
    }
    
    /**
     * 获取用户信息
     * 
     * @param int $userId 用户ID
     * @return array|false 用户信息数组或false
     */
    public function getUser($userId) {
        return $this->db->fetch("SELECT * FROM users WHERE id = ?", [$userId]);
    }
    
    /**
     * 搜索用户
     * 
     * @param string $keyword 搜索关键词
     * @param int $currentUserId 当前用户ID（排除自己）
     * @return array 用户列表
     */
    public function searchUsers($keyword, $currentUserId) {
        return $this->db->fetchAll(
            "SELECT id, username, nickname, avatar FROM users 
             WHERE (username LIKE ? OR nickname LIKE ?) AND id != ? 
             LIMIT 20",
            ["%$keyword%", "%$keyword%", $currentUserId]
        );
    }
    
    /**
     * 根据ID获取用户信息（getUser的别名）
     * 
     * @param int $userId 用户ID
     * @return array|false 用户信息数组或false
     */
    public function getUserById($userId) {
        return $this->getUser($userId);
    }
}
